<template>
    <view class="edit-sales-container">
        <view v-if="loading" class="loading-state">
            <u-loading-icon mode="circle" size="30"></u-loading-icon>
            <text>加载中...</text>
        </view>

        <template v-if="!loading && orderDetail">
            <!-- Basic Info -->
            <view class="info-section card">
                <view class="info-item clickable" @click="showDatePicker = true">
                    <view class="info-icon"><u-icon name="clock" size="20" color="#666666"></u-icon></view>
                    <text class="info-label">时间</text>
                    <view class="info-value">
                        <text>{{ formData.businessDate | formatDate }}</text>
                        <u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
                    </view>
                </view>
                <view class="info-item clickable" @click="selectPartner">
                    <view class="info-icon"><u-icon name="account" size="20" color="#666666"></u-icon></view>
                    <text class="info-label">客户</text>
                    <view class="info-value">
                        <text :class="{ 'placeholder': !selectedPartnerName }">
                            {{ selectedPartnerName || '请选择客户' }}
                        </text>
                        <u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
                    </view>
                </view>
            </view>

            <!-- Goods List -->
            <view class="selected-goods-section card">
                <view class="section-header">
                    <text class="section-title">选中货品 ({{ orderDetail.salesDetailItemList ?
                        orderDetail.salesDetailItemList.length : 0 }})</text>
                    <text class="section-total">合计金额: ¥{{ orderDetail.totalAmount | formatAmount }}</text>
                </view>
                <view class="selected-goods-list">
                    <view class="goods-item" v-for="(item, index) in formData.salesDetailItemList" :key="index">
                        <view class="goods-image">
                            <image :src="item.imageUrl || '/static/images/default-goods.png'" mode="aspectFill"></image>
                        </view>
                        <view class="goods-info">
                            <view class="goods-name">{{ item.goodsName || '未知商品' }}</view>
                            <view class="goods-detail">
                                <text class="goods-count">数量：{{ item.quantity || 0 }}</text>
                                <text class="goods-price">单价：¥ {{ item.unitPrice | formatAmount }}</text>
                            </view>
                            <view class="goods-amount">金额：¥ {{ item.totalPrice | formatAmount }}</view>
                        </view>
                    </view>
                </view>
                <view class="add-goods-btn" @click="addGoods">
                    <u-icon name="plus" size="40" color="#39C9BB"></u-icon>
                </view>
            </view>

            <!-- Settlement Info -->
            <view class="settlement-section card">
                <view class="settlement-item input-item">
                    <text class="settlement-label">{{orderDetail.discountType==="amount"?"优惠金额":"折扣率"}}</text>
                    <input type="number" class="settlement-input short-input" v-model="formData.discount"
                        placeholder="100" @input="onDiscountRateInput" />
                    <text class="percent-sign">{{orderDetail.discountType==="amount"?"":"%"}}</text>
                </view>
                <view class="settlement-item input-item">
                    <text class="settlement-label">折后金额</text>
                    <input type="number" class="settlement-input" v-model="formData.discountedAmount" placeholder="0.00"
                        @input="onDiscountedAmountInput" />
                </view>
                <view class="settlement-item input-item">
                    <text class="settlement-label">本单实收</text>
                    <input type="number" class="settlement-input" v-model="formData.actualPayment" placeholder="0.00"
                        @input="onActualPaymentInput" />
                </view>
                <view class="settlement-item clickable" @click="selectAccount">
                    <text class="settlement-label">结算账户</text>
                    <view class="settlement-value-select">
                        <text>{{ formData.paymentMethod }}</text>
                        <u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
                    </view>
                </view>
            </view>

            <!-- Remarks -->
            <view class="remark-section card">
                <view class="remark-header">
                    <text class="remark-label">备注</text>
                    <text class="remark-code">单号: {{ orderDetail.orderCode || '无' }}</text>
                </view>
                <view class="remark-content">
                    {{ orderDetail.remark || '无备注' }}
                </view>
            </view>
        </template>

        <view v-if="!loading && !orderDetail" class="empty-state">
            <u-empty mode="data" text="无法加载订单详情"></u-empty>
        </view>

        <!-- Bottom Actions -->
        <view class="bottom-actions">
            <button class="action-btn edit" @click="saveOrder">保存</button>
        </view>

        <!-- Delete Confirmation Modal -->
        <u-modal :show="deleteModalVisible" content="确定要删除该销售单吗？此操作不可恢复。" :showCancelButton="true"
            @confirm="deleteOrder" @cancel="deleteModalVisible = false"></u-modal>

        <!-- Pickers (Remove Discount Picker if not needed) -->
        <u-datetime-picker :show="showDatePicker" v-model="currentDate" mode="date" @confirm="confirmDate"
            @cancel="cancelPicker"></u-datetime-picker>
        <u-picker :show="showPartnerPicker" :columns="[partnerColumns]" keyName="label" @confirm="confirmPartner"
            @cancel="cancelPicker"></u-picker>
        <u-picker :show="showAccountPicker" :columns="[accountColumns]" keyName="label" @confirm="confirmAccount"
            @cancel="cancelPicker"></u-picker>
    </view>
</template>

<script>
import api from '@/utils/api.js';
// import dayjs from 'dayjs'; // 确保已安装并引入 dayjs

export default {
    data() {
        return {
            orderId: null,
            orderDetail: null,
            loading: true,
            deleteModalVisible: false,
            showDatePicker: false,
            showPartnerPicker: false,
            showAccountPicker: false,
            currentDate: Number(new Date()), // 用于日期选择器初始化
            selectedPartnerName: '',
            skipWatchers: false, // 添加标志控制是否跳过watch计算
            formData: {
                id: null,
                operation: 'sales',
                businessDate: '', // 初始化为今天
                customerId: null,
                customerName: '',
                salesDetailItemList: [],
                totalAmount: 0,
                discount: 0,
                discountType: 'amount',
                discountedAmount: 0,
                actualPayment: 0,
                remark: ''
            },
            partnerColumns: [], // 客户列表
            accountColumns: [ // 账户列表
                { label: '现金', value: '现金' },
                { label: '微信', value: '微信' },
                { label: '支付宝', value: '支付宝' },
                { label: '银行卡', value: '银行卡' },
                { label: '其他账户', value: '其他账户' }
            ],
            rules: {
                customerName: [
                    { required: true, message: '请输入客户名称', trigger: ['blur', 'change'] }
                ],
            }
        }
    },
    filters: {
        formatDate(value) {
            if (!value) return '';
            // Handles timestamp or date string
            try {
                const date = new Date(value);
                if (isNaN(date.getTime())) return value.toString().split('T')[0]; // Return original date part if invalid
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            } catch (e) {
                return value.toString().split('T')[0]; // Fallback
            }
        },
        formatAmount(value) {
            const num = Number(value);
            return isNaN(num) ? '0.00' : num.toFixed(2);
        }
    },
    computed: {
        totalAmount() {
            return this.formData.salesDetailItemList.reduce((sum, item) => {
                return sum + Number(item.finalPrice || 0);
            }, 0);
        }
    },
    watch: {
        'formData.salesDetailItemList': {
            handler() { 
                if (!this.skipWatchers) this.recalculateAmounts(); 
            },
            deep: true
        },
        'formData.discount': {
            handler() { 
                if (!this.skipWatchers) this.calculateDiscountedAmount(); 
            },
        },
        'formData.discountedAmount': {
            handler() { this.calculateDiscountRate(); },
        },
        'formData.discountedAmount': {
            handler(newVal, oldVal) {
                if (this.formData.actualPayment === oldVal) {
                    this.formData.actualPayment = newVal;
                }
            },
        }
    },
    onLoad(options) {
        if (options.id) {
            this.orderId = options.id;
            this.formData.id = options.id;
            this.loadOrderDetail(); // 先加载订单详情
        } else {
            // 如果是新增模式，也需要加载客户列表
            this.loading = false; // 不需要加载详情，设置 loading 结束
            uni.setNavigationBarTitle({ title: '新增销售单' }); // 设置默认标题
            console.error('缺少订单 ID，按新增处理（如果支持）或返回');
            // uni.navigateBack(); 
        }
        // **** 总是加载客户列表 ****
        this.loadPartners();
        
        uni.$on('confirmSelectGoods', this.handleGoodsSelection);
    },
    methods: {
        // 原生日期格式化为 YYYY-MM-DD
        formatDateToString(dateInput) {
            if (!dateInput) return '';
            try {
                const date = new Date(dateInput);
                if (isNaN(date.getTime())) { // 检查日期是否有效
                    console.error('Invalid date input for formatting:', dateInput);
                    return '';
                }
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            } catch (e) {
                console.error('Error formatting date:', dateInput, e);
                return '';
            }
        },
        // 统一加载初始数据
        async loadInitialData() {
            this.loading = true;
            try {
                const [orderRes, customerRes] = await Promise.all([
                    api.getSalesDetail(this.orderId),
                    api.listCustomer({ pageNum: 1, pageSize: 1000 })
                ]);
                console.log(orderRes)
                // 处理订单详情
                console.log("--- 销售单详情响应 (原始) ---", JSON.stringify(orderRes, null, 2));
                const detailData = orderRes.data || orderRes;
                if (detailData && typeof detailData === 'object') {
                    console.log("--- 解析后 detailData ---", JSON.stringify(detailData, null, 2));

                    const formattedDate = this.formatDateToString(detailData.businessDate) || this.formatDateToString(new Date());

                    // 填充表单数据
                    this.formData = {
                        ...this.formData,
                       ...detailData
                    };

                    this.currentDate = new Date(formattedDate).getTime();
                    console.log('更新后 formData:', JSON.stringify(this.formData, null, 2));
                    console.log('更新后 currentDate (时间戳):', this.currentDate);

                } else {
                    throw new Error('获取详情数据格式错误或为空');
                }

                // 处理客户列表 (放到 try 块内部)
                console.log("--- 客户列表响应 (原始) ---", JSON.stringify(customerRes, null, 2));
                const customerRows = customerRes.rows || customerRes;
                if (customerRows && Array.isArray(customerRows)) {
                    this.partnerColumns = customerRows.map(c => ({
                        label: c.customerName || c.name || '未命名',
                        value: c.id
                    }));
                    this.partnerColumns.unshift({ label: '零售客户', value: null });
                    console.log('--- 处理后 partnerColumns ---', JSON.stringify(this.partnerColumns, null, 2));
                    // **** 直接设置显示的名称 ****
                    this.setInitialSelectedPartnerName();
                } else {
                    console.warn('客户列表加载失败或格式错误');
                    this.partnerColumns = [{ label: '零售客户', value: null }];
                    this.setInitialSelectedPartnerName();
                }

            } catch (err) {
                console.error("加载初始数据失败:", err);
                uni.showToast({ title: `加载数据失败: ${err.message || '请检查网络'}`, icon: 'none' });
            } finally {
                this.loading = false;
            }
        },
        confirmAccount(e) {
            if (e && e.value && e.value.length > 0) {
                this.formData.paymentMethod = e.value[0].value; // 使用value
            }
            this.showAccountPicker = false;
        },
        // --- Picker 相关方法 --- 
        confirmDate(e) {
            console.log('confirmDate triggered, event:', JSON.stringify(e));
            if (!e || e.value === undefined) {
                console.error('Confirm date event missing value!');
                this.showDatePicker = false;
                return;
            }
            this.currentDate = e.value; // 更新选择器的 v-model (时间戳)
            this.formData.businessDate = this.formatDateToString(e.value); // 使用原生函数格式化显示/保存的日期
            console.log('Date updated: formData.businessDate:', this.formData.businessDate, 'currentDate:', this.currentDate);
            this.showDatePicker = false;
            console.log('Picker should be closed now, showDatePicker:', this.showDatePicker);
        },

        cancelPicker() {
            console.log('cancelPicker triggered');
            this.showDatePicker = false;
            this.showPartnerPicker = false;
            this.showAccountPicker = false;
            console.log('Pickers cancelled, showDatePicker:', this.showDatePicker);
        },
        // ... 其他方法 ...
        async loadOrderDetail() {
            this.loading = true;
            this.skipWatchers = true; // 禁用watchers防止自动计算
            console.log(`Fetching details for sales order ID: ${this.orderId}`);

            try {
                const res = await api.getSalesDetail(this.orderId)
                const detailData = res.data || res;
                console.log('API原始数据:', detailData);
                console.log('原始折后金额:', detailData.discountedAmount);
                
                // 确保折后金额是有效数字
                const safeDiscountedAmount = isNaN(Number(detailData.discountedAmount)) ? 0 : Number(detailData.discountedAmount);
                
                this.formData = {
                    ...this.formData,
                    ...detailData,
                    // 强制设置为有效数字
                    discountedAmount: safeDiscountedAmount
                }
                
                console.log('设置后formData:', this.formData);
                console.log('设置后折后金额:', this.formData.discountedAmount);
                
                // 使用setTimeout确保DOM更新后再次强制设置值
                setTimeout(() => {
                    this.formData.discountedAmount = safeDiscountedAmount;
                    console.log('setTimeout后折后金额:', this.formData.discountedAmount);
                    this.skipWatchers = false; // 重新启用watchers
                }, 300);
                
                if (detailData && typeof detailData === 'object') {
                    this.orderDetail = detailData;

                    if (this.orderDetail.customerId) {
                        console.log(`Fetching customer details for ID: ${this.orderDetail.customerId}`);
                        api.getCustomer(this.orderDetail.customerId)
                            .then(customerRes => {
                                console.log("Customer Detail Response:", customerRes);
                                const customerData = customerRes.data || customerRes;
                                if (customerData && customerData.customerName) {
                                    this.$set(this.orderDetail, 'customerName', customerData.customerName);
                                    console.log(`Updated customer name to: ${customerData.name}`);
                                } else {
                                    console.warn('Customer details fetched but name is missing or invalid format.');
                                    if (!this.orderDetail.customerName) {
                                        this.$set(this.orderDetail, 'customerName', '客户信息加载失败');
                                    }
                                }
                            })
                            .catch(customerErr => {
                                console.error(`Failed to fetch customer details for ID ${this.orderDetail.customerId}:`, customerErr);
                                if (!this.orderDetail.customerName) {
                                    this.$set(this.orderDetail, 'customerName', '客户信息加载失败');
                                }
                            });
                    } else {
                        if (!this.orderDetail.customerName) {
                            this.$set(this.orderDetail, 'customerName', '未指定客户');
                        }
                        console.log('No customerId found in order detail.');
                    }

                    if (!this.orderDetail.itemList) {
                        this.orderDetail.itemList = [];
                    }

                    this.loading = false;

                } else {
                    console.error("收到的订单详情数据格式无效");
                    uni.showToast({ title: '获取详情数据格式错误', icon: 'none' });
                    this.orderDetail = null;
                    this.loading = false;
                }
            } catch (err) {
                console.error("加载订单详情失败:", err);
                uni.showToast({ title: '加载详情失败，请重试', icon: 'none' });
                this.loading = false;
            }
        },
        saveOrder() {
            // 1. 基本校验
            // 检查客户是否已选择 (如果不是零售客户)
            if (!this.formData.customerId) {
                 uni.showToast({ title: '请选择客户', icon: 'none' });
                 return;
            }
            // 检查是否至少有一个商品
            if (!this.formData.salesDetailItemList || this.formData.salesDetailItemList.length === 0) {
                 uni.showToast({ title: '请至少选择一个商品', icon: 'none' });
                 return;
            }
            // 您可以在这里添加更多校验，例如检查金额是否有效等

			uni.showLoading({ title: '保存中...' });

            // 2. 准备提交的数据 (确保字段与后端更新接口匹配)
            const postData = {
                id: this.orderId, // **** 关键：包含订单ID ****
                ...this.formData,
                totalAmount: this.orderDetail.totalAmount,
                // 传递商品明细，确保包含必要信息，特别是可能需要的 item.id
                salesDetailItemList: this.formData.salesDetailItemList.map(item => ({
                    id: item.id || null, // **** 很重要：如果后端需要明细ID来更新或删除特定行 ****
                    goodsId: item.goodsId,
                    goodsCode: item.goodsCode || '',
                    goodsName: item.goodsName || '',
                    goodsSpec: item.goodsSpec || '',
                    quantity: Number(item.quantity || 0),
                    unitPrice: Number(item.unitPrice || 0),
                    totalPrice: Number(item.totalPrice || 0), // 基于(数量*单价)
                    finalPrice: Number(item.finalPrice || 0), // 通常等于totalPrice，除非有行折扣
                    discount: Number(item.discount || 100) // 行折扣率 (如果支持)
                }))
            };
            console.log('postData',postData,this.orderDetail.totalAmount)
             // 移除仅前端使用的 customerName (如果后端不需要)
             // delete postData.customerName;
            console.log(postData)
            console.log("准备更新销售单数据:", JSON.stringify(postData, null, 2));

            // 3. 调用更新 API (用您的实际函数替换 updateSalesOrder)
            api.updateSales(this.formData)
               .then(res => {
                   uni.hideLoading();
                   console.log('更新销售单响应:', res);
                //    if (res.code === 200) { // **根据您的 API 响应调整成功判断**
                       uni.showToast({ title: '修改成功', icon: 'success' });
                       // 通知列表页和详情页刷新
                       uni.$emit('refreshDetailList', { type: this.formData.operation }); // 通知列表刷新
                       // uni.$emit('refreshSalesDetail', { id: this.orderId }); // 可选：通知详情页也刷新
                       setTimeout(() => {
                           uni.navigateBack(); // 返回上一页 (通常是详情页)
                       }, 1500);
                //    } else {
                //        uni.showToast({ title: res.msg || '修改失败', icon: 'none' });
                //    }
               })
               .catch(err => {
                   uni.hideLoading();
                   console.error("更新销售单失败:", err);
                   uni.showToast({ title: '修改失败，请重试', icon: 'none' });
               });
		},
        confirmDeleteOrder() {
            this.deleteModalVisible = true;
        },
        deleteOrder() {
            if (!this.orderId) return;
            uni.showLoading({ title: '删除中...' });
            console.log(`正在删除销售订单 ID: ${this.orderId}`);

            api.deleteSalesOrder(this.orderId)
                .then(res => {
                    uni.hideLoading();
                    if (res.code === 200 || res.success) {
                        uni.showToast({ title: '删除成功', icon: 'success' });
                        uni.$emit('refreshDetailList', { type: 'outbound' });
                        setTimeout(() => {
                            uni.navigateBack();
                        }, 1500);
                    } else {
                        console.error("删除失败，API 响应:", res);
                        uni.showToast({ title: res.msg || '删除失败', icon: 'none' });
                    }
                })
                .catch(err => {
                    console.error("删除销售订单失败:", err);
                    uni.hideLoading();
                    uni.showToast({ title: '删除失败，请重试', icon: 'none' });
                });
        },
        selectPartner() {
            this.showPartnerPicker = true;
        },
        selectAccount() {
            this.showAccountPicker = true;
        },
        addGoods() {
            uni.navigateTo({
                url: '/pages/goods/select'
            });
        },
        setSelectedGoods(goods, amount) { // This now needs to update currentState
            // Update the *current* state object
            console.log("--- 选择商品 ---", goods,amount)
            // this.currentState.selectedGoodsList = goods;
            // this.currentState.selectedGoodsCount = goods.length;
            this.orderDetail.totalAmount = amount;

            // Calculate discount based on the current state
            // this.calculateDiscount(); // Needs to use currentState too
            this.formData.salesDetailItemList = goods.map(item => ({
                ...item,
                goodsId: item.id,
                goodsCode: item.id,
                goodsName: item.name,
                unitPrice: item.price,
                totalPrice: item.price * item.quantity,
                // finalPrice: item.price * item.quantity,
            }));
            this.recalculateAmounts()
            uni.showToast({
                title: `已选择${goods.length}种商品`,
                icon: 'none',
                duration: 1500
            });
        },
        onDiscountedAmountInput() {
            // Implementation of handling discounted amount input
        },
        onDiscountRateInput() {
            // Implementation of handling discount rate input
        },
        onActualPaymentInput() {
            // Implementation of handling actual payment input
        },
        confirmPartner(e) {
            console.log('confirmPartner event:', JSON.stringify(e, null, 2)); 
            let determinedLabel = '选择错误';
            let determinedValue = null;

            // 优先尝试从 e.value[0] (可能是完整对象) 获取
            if (e && e.value && Array.isArray(e.value) && e.value.length > 0) {
                const selectedItem = e.value[0];
                // 检查 value[0] 是否为我们期望的对象格式 {label: ..., value: ...}
                if (typeof selectedItem === 'object' && selectedItem !== null && selectedItem.label !== undefined && selectedItem.value !== undefined) {
                    determinedLabel = selectedItem.label;
                    determinedValue = selectedItem.value; // value 应该是 ID
                    console.log('使用 e.value[0] 对象获取');
                } 
                // 如果 e.value[0] 不是对象，但 e.label 存在 (uView 可能返回分开的数组)
                else if (e.label && Array.isArray(e.label) && e.label.length > 0) {
                     determinedLabel = e.label[0];
                     determinedValue = selectedItem; // 此时 selectedItem 是 e.value[0]
                     console.log('使用 e.label[0] 和 e.value[0] 获取');
                } 
                // 如果连 label 都没有，直接用 value[0]
                else {
                     determinedLabel = selectedItem ? selectedItem.toString() : '值错误';
                     determinedValue = selectedItem; // 此时 value 可能是 ID
                     console.warn('缺少 label，直接使用 value[0]');
                }
            } 
            // 如果 value 结构不对，尝试用 indexs
            else if (e && e.indexs && Array.isArray(e.indexs) && e.indexs.length > 0) {
                const selectedIndex = e.indexs[0];
                if (selectedIndex >= 0 && selectedIndex < this.partnerColumns.length) {
                    const selectedItemFromIndex = this.partnerColumns[selectedIndex];
                    if (selectedItemFromIndex && selectedItemFromIndex.label !== undefined && selectedItemFromIndex.value !== undefined) {
                        determinedLabel = selectedItemFromIndex.label;
                        determinedValue = selectedItemFromIndex.value; // value 是 ID
                        console.log('使用 e.indexs[0] 获取');
                    } else {
                         console.error('根据索引找到的项目无效:', selectedItemFromIndex);
                    }
                } else {
                     console.error('选择的索引越界:', selectedIndex);
                }
            } else {
                console.error('选择器确认事件结构异常:', e);
            }

            this.selectedPartnerName = determinedLabel;    // 更新显示名称
            this.formData.customerId = determinedValue; // 更新客户 ID
            // 如果需要，可以同步 formData 中的 customerName
            // this.formData.customerName = determinedLabel; 
            console.log(`已选择客户: ${this.selectedPartnerName}, ID: ${this.formData.customerId}`);

			this.showPartnerPicker = false;
            // 验证字段 (如果需要)
            // this.$refs.uForm.validateField('customerId'); 
		},
        recalculateAmounts(ignoreExisting = false) {
            // 重新计算合计金额
            const newTotal = this.formData.salesDetailItemList.reduce((sum, item) => {
                return sum + Number(item.totalPrice || 0);
            }, 0);
            
            // 如果ignoreExisting为true且已有折后金额值，则不覆盖
            if (!ignoreExisting || !Number(this.formData.discountedAmount)) {
                // 重新计算折后金额
                const rate = Number(this.formData.discount);
                this.formData.discountedAmount = this.formData.discountType==="amount"?newTotal-rate:((newTotal * (rate / 100)).toFixed(2));
                console.log(`重新计算折后金额：${this.formData.discountedAmount}, 原始金额：${newTotal}, 折扣：${rate}`);
            } else {
                console.log(`保留原有折后金额：${this.formData.discountedAmount}`);
            }
        },
        calculateDiscountedAmount() {
            const total = this.totalAmount;
            const rate = Number(this.formData.discount) || 100;
            this.formData.discountedAmount = (total * (rate / 100)).toFixed(2);
        },
        calculateDiscountRate() {
            const total = this.totalAmount;
            const discounted = Number(this.formData.discountedAmount) || 0;
            if (total > 0) {
                this.formData.discountRate = ((discounted / total) * 100).toFixed(2);
            } else {
                this.formData.discountRate = 100.00;
            }
        },
        handleQuantityChange(item) {
            item.quantity = Number(item.quantity) || 1;
            item.finalPrice = (item.quantity * Number(item.unitPrice || 0)).toFixed(2);
        },
        updateSalesOrder() {
            if (!this.formData.customerId && this.selectedPartnerName !== '零售客户') {
                uni.showToast({ title: '请选择客户', icon: 'none' }); return;
            }
            if (!this.formData.salesDetailItemList || this.formData.salesDetailItemList.length === 0) {
                uni.showToast({ title: '请至少选择一个商品', icon: 'none' }); return;
            }

            uni.showLoading({ title: '保存中...' });



            console.log("更新销售单数据:", postData);

            api.updateSalesOrder({...this.formData})
                .then(res => {
                    // ... (Keep existing success/error handling) ...
                })
                .catch(err => {
                    // ... (Keep existing error handling) ...
                });
        },
        // **** 添加加载客户列表的方法 ****
        loadPartners() {
            console.log('开始加载客户列表...');
            uni.showLoading({ title: '加载客户...' });
            api.listCustomer({ pageNum: 1, pageSize: 1000 }) // 获取客户
                .then(res => {
                    uni.hideLoading();
                    console.log("客户列表响应:", res);
                    const customerRows = res.rows || res; // 适配直接返回数组或带rows的情况
                    if (customerRows && Array.isArray(customerRows)) {
                        this.partnerColumns = customerRows.map(c => ({
                            label: c.customerName || c.name || '未命名客户', // 检查可能的字段名
                            value: c.id // 假设ID字段是id
                        })).filter(c => c.value !== undefined && c.value !== null); // 过滤无效ID
                        this.partnerColumns.unshift({ label: '零售客户', value: null }); // 添加默认选项
                        console.log('处理后的客户列表 (partnerColumns):', this.partnerColumns);
                        
                        // 客户列表加载后，尝试设置初始名称（如果编辑状态）
                        this.setInitialSelectedPartnerName(); 
                    } else {
                        console.error('客户列表加载失败或格式错误');
                        uni.showToast({ title: '加载客户列表失败', icon: 'none' });
                        this.partnerColumns = [{ label: '零售客户', value: null }];
                        this.setInitialSelectedPartnerName(); 
                    }
                })
                .catch(err => {
                    uni.hideLoading();
                    console.error('加载客户列表接口失败:', err);
                    uni.showToast({ title: '加载客户列表出错', icon: 'none' });
                    this.partnerColumns = [{ label: '零售客户', value: null }];
                    this.setInitialSelectedPartnerName(); 
                });
        },
        // **** 结束添加 ****
        // 根据加载的 customerId 设置初始显示的客户名称
        setInitialSelectedPartnerName() {
            console.log(`[setInitialSelectedPartnerName] 开始设置名称, customerId: ${this.formData.customerId}, partnerColumns available: ${this.partnerColumns && this.partnerColumns.length > 0}`);
            if (this.formData.customerId) {
                if (this.partnerColumns && this.partnerColumns.length > 0) {
                    // 查找使用 value (现在应该是 ID)
                    const found = this.partnerColumns.find(p => p.value === this.formData.customerId);
                    if (found) {
                        this.selectedPartnerName = found.label;
                        console.log("[Initial Set] 找到匹配项，设置为:", this.selectedPartnerName);
                    } else {
                        this.selectedPartnerName = this.formData.customerName || `未知客户 (ID: ${this.formData.customerId})`;
                        console.warn(`[Initial Set] 未在列表中找到 ID ${this.formData.customerId}，使用 API 返回的名称或提示`);
                    }
                } else {
                    this.selectedPartnerName = this.formData.customerName || '加载中...';
                    console.log("[Initial Set] 列表未就绪，临时名称:", this.selectedPartnerName);
                }
            } else {
                this.selectedPartnerName = '零售客户'; 
                console.log("[Initial Set] 没有客户 ID，设为默认:", this.selectedPartnerName);
            }
        },
    }
}
</script>

<style lang="scss" scoped>
page {
    background-color: #f5f7fa;
}

.edit-sales-container {
    padding: 20rpx;
    padding-bottom: 140rpx;
    /* 为固定的底部操作按钮留出空间 */
}

.loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    color: #909399;
    font-size: 28rpx;

    text {
        margin-top: 10rpx;
    }
}

.card {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

/* Info Section */
.info-section {
    .info-item {
        display: flex;
        align-items: center;
        min-height: 70rpx;
        padding: 10rpx 0;

        &:not(:last-child) {
            border-bottom: 1rpx solid #f0f0f0;
        }

        .info-icon {
            margin-right: 15rpx;
        }

        .info-label {
            font-size: 28rpx;
            color: #333333;
            width: 140rpx;
        }

        .info-value {
            flex: 1;
            font-size: 28rpx;
            color: #666666;
            text-align: right;
        }
    }
}

/* Goods Section */
.selected-goods-section {
    padding: 0;

    /* 移除卡片内边距以使头部/列表占满宽度 */
    .section-header {
        display: flex;
        justify-content: space-between;
        padding: 25rpx 30rpx;
        border-bottom: 1rpx solid #eeeeee;

        .section-title,
        .section-total {
            font-size: 28rpx;
            color: #333333;
        }
    }

    .selected-goods-list {
        padding: 10rpx 30rpx 30rpx;

        /* Add padding around items */
        .goods-item {
            display: flex;
            padding: 20rpx 0;

            &:not(:last-child) {
                border-bottom: 1rpx solid #f0f0f0;
            }

            .goods-image {
                width: 100rpx;
                height: 100rpx;
                margin-right: 20rpx;
                flex-shrink: 0;

                image {
                    width: 100%;
                    height: 100%;
                    border-radius: 8rpx;
                    background-color: #f5f5f5;
                }
            }

            .goods-info {
                flex: 1;
                display: flex;
                flex-direction: column;

                .goods-name {
                    font-size: 28rpx;
                    color: #333333;
                    margin-bottom: 10rpx;
                }

                .goods-detail {
                    display: flex;
                    margin-bottom: 10rpx;

                    .goods-count,
                    .goods-price {
                        font-size: 24rpx;
                        color: #666666;
                        margin-right: 30rpx;
                    }
                }

                .goods-amount {
                    font-size: 24rpx;
                    color: #666666;
                }
            }
        }
    }
    .add-goods-btn{
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20rpx 0;
        border-top: 1rpx solid #eeeeee;
        
    }
}

/* Settlement Section */
.settlement-section {
    .settlement-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        min-height: 70rpx;
        padding: 15rpx 0;

        &:not(:last-child) {
            border-bottom: 1rpx solid #f0f0f0;
        }

        .settlement-label {
            font-size: 28rpx;
            color: #333333;
        }

        .settlement-value {
            font-size: 28rpx;
            color: #666666;
        }
    }
}

/* Remark Section */
.remark-section {
    .remark-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15rpx;

        .remark-label {
            font-size: 28rpx;
            color: #333;
        }

        .remark-code {
            font-size: 24rpx;
            color: #999;
        }
    }

    .remark-content {
        font-size: 28rpx;
        color: #666;
        line-height: 1.6;
        background-color: #f8f8f8;
        padding: 20rpx;
        border-radius: 8rpx;
        min-height: 100rpx;
    }
}

.empty-state {
    padding-top: 150rpx;
}

/* Bottom Actions */
.bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    height: 100rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    padding: 10rpx 20rpx;
    box-sizing: border-box;
    z-index: 10;

    .action-btn {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 30rpx;
        border-radius: 12rpx;
        margin: 0 10rpx;
        border: none;

        &::after {
            border: none;
        }

        &.delete {
            background-color: #fff1f0;
            color: #ff4d4f;
            border: 1rpx solid #ffa39e;
        }

        &.edit {
            background-color: #3ACBC1; // 使用您的主题色
            color: #fff;
        }
    }
}

/* Add/Adjust styles for clickable items and inputs */
.clickable {
    cursor: pointer;

    &:active {
        // 添加触摸反馈
        background-color: #f8f8f8;
    }
}

.info-item.clickable .info-value,
.settlement-item.clickable .settlement-value-select {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    /* Align arrow to right */
}

.settlement-item.input-item {
    align-items: center;
    /* Align label and input */
}

.settlement-input {
    font-size: 28rpx;
    color: #666;
    text-align: right;
    flex: 1;
    margin-left: 20rpx;
    /* Basic input styling */
    padding: 5rpx 0;
    min-width: 100rpx;
    /* Ensure some minimum width */
    border: none;
    background-color: transparent;
}

.settlement-input.short-input {
    // flex: none;
    /* Don't let it grow too much */
    width: 120rpx;
    /* Fixed width for rate */
}

.percent-sign {
    font-size: 28rpx;
    color: #666;
    margin-left: 5rpx;
}

/* Adjust goods list item styles */
.selected-goods-list .selected-goods-item {
    align-items: center;

    /* Vertically center align all items */
    .selected-goods-info {
        /* Adjust layout if needed */
    }

    .delete-item-btn {
        padding: 10rpx;
        margin-left: 10rpx;
        /* Space from info */
        align-self: center;

        /* Center vertically */
        &:active {
            // 添加触摸反馈
            background-color: #f0f0f0;
            border-radius: 50%;
        }
    }
}

/* Quantity Editor in goods list */
.quantity-editor {
    display: flex;
    align-items: center;
    color: #666666;
    font-size: 24rpx;
    margin-bottom: 10rpx;

    text {
        margin-right: 10rpx;
    }
}

/* Bottom button adjustments if needed */
.bottom-btn {
    // ... existing styles ...
}

/* Picker Popup Styles (Copied from add.vue) */
.popup-container {
    /* ... */
}

.popup-header {
    /* ... */
}

.popup-content {
    /* ... */
}

.popup-item {
    /* ... */
}

.popup-empty {
    /* ... */
}
</style>